package com.qx.chat.system.service;

import static org.springframework.data.mongodb.core.aggregation.Aggregation.group;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.limit;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.match;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.newAggregation;
import static org.springframework.data.mongodb.core.aggregation.Aggregation.sort;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qx.chat.system.dao.AbstractRepository;
import com.qx.chat.system.entity.Band;
import com.qx.chat.system.entity.ChatMessageRecord;
import com.qx.chat.system.entity.GroupUser;
import com.qx.chat.system.entity.RecentContacts;
import com.qx.chat.system.entity.User;

/**
 * TODO
 * 
 * @author cyf
 * @version TODO
 */
@Component
public class ContactsServiceImpl implements ContactsService {
	@Autowired
	private AbstractRepository<ChatMessageRecord> chatRecordDaoImpl;
	@Autowired
	private AbstractRepository<User> userDaoImpl;
	@Autowired
	private AbstractRepository<Band> bandDaoImpl;
	@Autowired
	private AbstractRepository<GroupUser> groupUserDaoImpl;
	@Autowired
	private OrgService orgServiceImpl;
	/**
	 * 取二十个最近联系人
	 */
	@Override
	public JSONArray getRecentContactsTreeDataByLoginName(String loginName) {
		User user = userDaoImpl.findOne("loginName", loginName);
		Criteria criteria = new Criteria().orOperator(Criteria.where("audienceUserId").is(user.getId()),
				Criteria.where("speakerUserId").is(user.getId())).andOperator(Criteria.where("chatType").is(0));
		MongoTemplate mongoTemplate = chatRecordDaoImpl.getMongoTemplate();
		AggregationResults<RecentContacts> aggregate = null;
		Aggregation aggregation = newAggregation(match(criteria), sort(Sort.Direction.ASC, "occureTime"),
				group("audienceUserId", "speakerUserId"), limit(20));
		aggregate = mongoTemplate.aggregate(aggregation, ChatMessageRecord.class, RecentContacts.class);
		Iterator<RecentContacts> it = aggregate.iterator();
		JSONArray arr = new JSONArray();
		while (it.hasNext()) {
			RecentContacts record = it.next();
			User speaker = record.getSpeakerUser();
			User audienceUser = record.getAudienceUser();

			JSONObject jo = new JSONObject();
			if (StringUtils.equals(audienceUser.getLoginName(), loginName)) {
				jo.put("id", speaker.getId());
				jo.put("loginName", speaker.getLoginName());
				jo.put("name", speaker.getNickname());
			}
			if (StringUtils.equals(speaker.getLoginName(), loginName)) {
				jo.put("id", audienceUser.getId());
				jo.put("loginName", audienceUser.getLoginName());
				jo.put("name", audienceUser.getNickname());
			}
			jo.put("pId", null);
			jo.put("isParent", false);
			if(orgServiceImpl.isOnline(jo.getString("id"))){
				jo.put("status", 1);
			}else{
				jo.put("status", 0);
			}
			arr.add(jo);
		}
		return arr;
	}
	@Override
	public JSONArray getPersonalBandTreeDataByLoginName(String loginName) {
		User user = userDaoImpl.findOne("loginName", loginName);
		Criteria c = Criteria.where("owner").is(user.getId());
		List<Order> orders = new ArrayList<Order>();
		orders.add(new Order(Direction.DESC, "order"));
		List<Band> findList = bandDaoImpl.findList(c,orders);
		JSONArray treeDataArr = new JSONArray();
		for (Band band : findList) {
			JSONObject jo = new JSONObject();
			jo.put("id", band.getId());
			jo.put("name", band.getName());
			jo.put("pId", null);
			jo.put("click", false);
			jo.put("isParent", true);
			List<User> members = band.getMembers();
			if(members!=null&&members.size()>0){
				JSONArray ua = new JSONArray();
				for (User u : members) {
					JSONObject joo = new JSONObject();
					joo.put("id", u.getId());
					joo.put("loginName", u.getLoginName());
					joo.put("name", u.getNickname());
					joo.put("pId", band.getId());
					joo.put("isParent", false);
					if(orgServiceImpl.isOnline(u.getId())){
						joo.put("status", 1);
					}else{
						joo.put("status", 0);
					}
					ua.add(joo);
				}
				jo.put("children", ua);
			}
			treeDataArr.add(jo);
		}
		return treeDataArr;
	}

	@Override
	public JSONArray getGroupTreeDataByLoginName(String loginName) {
		User user = userDaoImpl.findOne("loginName", loginName);
		Criteria c = Criteria.where("user").is(user.getId());
		List<Order> orders = new ArrayList<Order>();
		orders.add(new Order(Direction.DESC, "order"));
		List<GroupUser> findList = groupUserDaoImpl.findList(c,orders);
		JSONArray treeDataArr = new JSONArray();
		for (GroupUser gu : findList) {
			JSONObject jo = new JSONObject();
			jo.put("id", gu.getGroup().getId());
			jo.put("name", gu.getGroup().getName());
			jo.put("pId", null);
			jo.put("isParent", false);
			treeDataArr.add(jo);
		}
		return treeDataArr;
	}
}
